/**
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.solarchallenge.client.gwtui.applicants.register.signup;

import static com.google.solarchallenge.shared.Utils.RedirectionUtils.generateValidParamsToAttach;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.solarchallenge.client.event.EventCategory;
import com.google.solarchallenge.client.event.HistoryHandler;
import com.google.solarchallenge.client.gwtui.mvpinterfaces.Presenter;
import com.google.solarchallenge.client.rpc.ServiceProvider;
import com.google.solarchallenge.shared.ValidParams;
import com.google.solarchallenge.shared.dtos.ApplicantDto;
import com.google.solarchallenge.shared.dtos.UserAccountDto;
import com.google.solarchallenge.shared.dtos.UsAddressDto;

/**
 * Presenter for Registering a new Applicant.
 *
 * @author Arjun Satyapal
 */
public class ApplicantRegisterPresenter extends Presenter {
  private final ApplicantRegisterDisplay display;

  public ApplicantRegisterPresenter(ApplicantRegisterDisplay display,
      String historyToken) {
    super(display.getSolarChallengeHeaderPanel(), historyToken);
    this.display = display;
  }

  @Override
  public void go(HasWidgets container) {
    container.clear();
    container.add(display.asWidget());
    bind();
  }

  @Override
  public void bind() {
    display.getButtonCancel().addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        // TODO(arjuns): See if there is better place to send back.
        HistoryHandler.handleNewToken(EventCategory.HOME.getToken());
      }
    });

    display.getButtonSave().addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent event) {
        UserAccountDto userAccountDto = display.getContactDetailsWidget()
            .getValuesAsDto();
        UsAddressDto usAddressDto = display.getUsAddressDisplayWidget()
            .getValuesAsDto();

        ApplicantDto dto = new ApplicantDto.Builder().setUsAddressDto(
            usAddressDto).build();
        ServiceProvider
            .getServiceProvider()
            .getApplicantService()
            .registerApplicant(userAccountDto, dto,
                getApplicantRegisterCallback());
      }

      private AsyncCallback<Void> getApplicantRegisterCallback() {
        display.setEnabled(false);
        // TODO(arjuns) : Add servlet saying user already exists.
        AsyncCallback<Void> callback = new AsyncCallback<Void>() {
          @Override
          public void onFailure(Throwable caught) {
            display.setEnabled(true);

            // TODO(arjuns) : Add proper exception handling here.
            Window.alert("Failed to register the user. Reason[" + caught
                .getLocalizedMessage() + "].");
          }

          @Override
          public void onSuccess(Void result) {
            String token = HistoryHandler.createTokenWithParams(
                EventCategory.LOGIN_UI,
                generateValidParamsToAttach(ValidParams.CLIENT_CALLBACK_TOKEN,
                    EventCategory.APPLICANT_AGREEMENT.getToken()));
            HistoryHandler.handleNewToken(token);
          }
        };

        return callback;
      }
    });
  }
}
